﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Service.Core.Identity.Model;
using System.Security.Claims;

namespace Service.Core.Identity
{
    public class CustomAuthorizationService : DefaultAuthorizationService
    {
        public CustomAuthorizationService(IAuthorizationPolicyProvider policyProvider, IAuthorizationHandlerProvider handlers, ILogger<DefaultAuthorizationService> logger, IAuthorizationHandlerContextFactory contextFactory, IAuthorizationEvaluator evaluator, IOptions<AuthorizationOptions> options) : base(policyProvider, handlers, logger, contextFactory, evaluator, options)
        {
        }

        public override async Task<AuthorizationResult> AuthorizeAsync(ClaimsPrincipal user, object? resource, IEnumerable<IAuthorizationRequirement> requirements)
        {
            // 如果方法级别有策略，直接执行方法级别的策略
            var innerRequirement = requirements.FirstOrDefault(s => s.GetType().Equals(typeof(InnerRequirement)));
            if (innerRequirement is not null)
            {
                return await base.AuthorizeAsync(user, resource, new List<IAuthorizationRequirement>() { innerRequirement });
            }
            // 如果方法级别没有策略，执行默认的授权逻辑
            return await base.AuthorizeAsync(user, resource, requirements);
        }
    }
}
